package com.lzm.Controller;

import com.lzm.bean.Message;
import com.lzm.mvc.ResponseBody;
import com.lzm.service.AdminService;
import com.lzm.util.JSONUtil;
import com.lzm.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class AdminController {

    @ResponseBody("/admin/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        //1.接参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2. 调用service传参数，并获取结果
        boolean result = AdminService.login(username, password);
        //3. 根据结果，准备不同的返回数据
        Message msg = null;
        if(result){
            msg = new Message(0,"登录成功");//{status:0,result:"登录成功"}
            //登录时间和ip的更新
            Date date = new Date();
            String ip = request.getRemoteAddr();
            AdminService.updateLoginTimeAndIp(username,date,ip);
            request.getSession().setAttribute("adminUserName",username);
        }else {
            msg = new Message(-1,"登录失败");//{status:-1,result:"登录失败"}
        }
        //4. 将数据转换为JSON
        String json = JSONUtil.toJSON(msg);
        //5. 将数据回复给ajax
        return json;
    }

    @ResponseBody("/admin/loginOut.do")
    public String loginOut(HttpServletRequest request,HttpServletResponse response){
         request.getSession().invalidate();
         Message msg = new Message(0,"退出成功");
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/admin/getName.do")
    public String getName(HttpServletRequest request, HttpServletResponse response){
        String userName = UserUtil.getUserName(request.getSession());
        Message msg = new Message();
        msg.setStatus(0);
        msg.setResult("查询成功");
        msg.setData(userName);
        String json = JSONUtil.toJSON(msg);
        return json;
    }
}
